<?php

namespace App\Http\Middleware;

use Closure;

class PermissionAutoMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (\Auth::guest()) {
            return redirect('/');
        }

        if ($request->user()->isAdmin()) {
            return $next($request);
        }

        $actionName = preg_split('/@/', basename(str_replace('\\', '/', $request->route()->getActionName())));
        $moduleName = preg_replace('/Controller$/', '', $actionName[0]);
        $methodName = $actionName[1];
        if ($methodName == 'bundle') {
            $actionName = $request->input('action');
            if ($actionName == 'delete') {
                $actionName = 'destroy';
            }
            $permission = $moduleName . ',' . $actionName;
        } else {
            $permission = $moduleName . ',' . $actionName[1];
        }
        if ($request->user()->can($permission)) {
            return $next($request);
        }

        abort(403, '您没有权限操作');
    }
}
